from llmtcg.chat.models.openai import OpenaiCompatibleChatModel

from typing import Any, Dict, Tuple
from os import environ
from dataclasses import dataclass
from enum import Enum

from llmtcg.utils.profiler import Currency


@dataclass
class MoonshotChatModel(OpenaiCompatibleChatModel):

    """ Support for moonshot series models """

    class Model(Enum):
        MOONSHOT_V1_8K = "moonshot-v1-8k"
        MOONSHOT_V1_32K = "moonshot-v1-32k"
        MOONSHOT_V1_128K = "moonshot-v1-128k"

    api_key: str = environ.get("MOONSHOT_API_KEY", "")
    model: Model = Model.MOONSHOT_V1_32K

    @property
    def api_address(self) -> str:
        return "https://api.moonshot.cn/v1"

    @property
    def headers(self) -> Dict[str, str]:
        return {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

    @property
    def model_name(self) -> str:
        return self.model.value

    @property
    def support_tool_use(self) -> bool:
        return True

    def price(self) -> Tuple[float, float, Currency]:
        if self.model is self.Model.MOONSHOT_V1_8K:
            return (12, 12, Currency.CNY)
        if self.model is self.Model.MOONSHOT_V1_32K:
            return (24, 24, Currency.CNY)
        if self.model is self.Model.MOONSHOT_V1_128K:
            return (60, 60, Currency.CNY)

    def detect_error(self, response: Any) -> Tuple[bool, str]:
        if 'code' in response:
            if response['code'] == 10003:
                return True, f"authentication error, please check API_KEY (current value is {self.api_key})"

        return False, ""

    def __hash__(self) -> int:
        return id(self)
